//
//  TableVC.m
//
//
//  Created by mac on 15/4/17.
//
//

#import "TableVC.h"
#import "ADWebViewController.h"
#import "Util.h"
#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0)//1
@interface TableVC ()<PageScrollDelegate,EGORefreshTableHeaderDelegate,UIScrollViewDelegate>{
    PageControlScrollView*Pscroll;//头图
    
    NSMutableArray *_userData;//所有数据
    NSMutableArray* topArray;//头图数据
    BOOL isLoading;//是否在刷新
    //    NSString*slugKey;
    //    NSString*downlad_URL;
    BOOL reloading;//
    int _page;//页码
    
    int number;
    UIView *ButtonView;
    UIButton *changeCityButton;
    
    NSArray *cityArray;
    
    UITableView  *theTableView;
}
@property(nonatomic,strong)EGORefreshTableHeaderView * refreshHeaderView;

@end

@implementation TableVC
@synthesize refreshHeaderView=_refreshHeaderView;


- (void)viewDidLoad {
    [super viewDidLoad];
    [self initData];
    [self initPscroll];
    
//    UITabBarController * tabController = [[UITabBarController alloc] init];
//    
//    tabController.tabBar.backgroundColor = [UIColor whiteColor];
//    
//    self.tabBarController.tabBar.barTintColor = [UIColor blackColor];
////    self.tabBarController.tabBar.translucent = true;
//    self.tabBarController.tabBar.tintColor = [UIColor blueColor];
//    
//    
//    self.tabBarController.tabBar.barStyle = UIBarStyleBlack;//使标签栏黑色
    
    
    
    
//    [self loadNews];
    
    
//    NSURL *url = [NSURL URLWithString:@"http://ksjv2.kanshangjie.com/Category/News"];
    
//    dispatch_async(kBgQueue, ^{
//        NSData* data = [NSData dataWithContentsOfURL:url];//直接读取url中的数据
//        NSLog(@" --- data ---%@",data);
//        [self performSelectorOnMainThread:@selector(fetchedData:) withObject:data waitUntilDone:YES];//在主线程中调用fetchedData方法
//    });

    
    
    
    
    //2.单例 取出数据---本地的多一排的按钮显示
//    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
//    number = [userDefault integerForKey:@"tablePageIntegar"];
//    NSLog(@"number == ++ %ld",(long)number);

    //接收通知的设置,接收各种目标在设置的通知--已切换城市，现在刷新界面
//    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadNews) name:@"showTheNewCity" object:nil];//都是nil

}

- (void)fetchedData:(NSData *)responseData {
    //parse out the json data
    NSLog(@"responseData == %@",responseData);
    NSError* error;
    NSDictionary* json = [NSJSONSerialization
                          JSONObjectWithData:responseData //1
                          options:NSJSONReadingAllowFragments
                          error:&error];
    
    NSArray* employees = [json objectForKey:@"employees"]; //2
    
    NSDictionary  *testDic = [json objectForKey:@"data"];
    NSLog(@" testDic == %@",testDic);
    
    NSLog(@"employees: %@", employees); //3
    //    jsonText.text = [NSString stringWithFormat:@"employees:%@",employees];
    
    NSMutableString *str = [NSMutableString stringWithCapacity:40];
    for (NSDictionary *employee in employees) {
        NSLog(@"employee's first name is %@,last name is %@",[employee objectForKey:@"firstName"],[employee objectForKey:@"lastName"]);
        [str appendString:[NSString stringWithFormat:@"employee's first name is %@,last name is %@\n",[employee objectForKey:@"firstName"],[employee objectForKey:@"lastName"]]];
        NSLog(@"%@",str);
    }
    
    //    humanReadableText.text = str;
}


//初始化四个本地的按钮
- (void)initFourButton{
    NSMutableArray *buttonNameArray = [NSMutableArray arrayWithObjects:@"论坛",@"游学",@"咨询",@"创投",nil];
    NSMutableArray *buttonPhotoArray = [NSMutableArray arrayWithObjects:@"luntan",@"youxue",@"咨询",@"chuangtou",nil];
    
    ButtonView = [[UIView alloc] initWithFrame:CGRectMake(0, Pscroll.frame.origin.y + Pscroll.frame.size.height, self.view.frame.size.width, 80)];
    
    int a = self.view.frame.size.width / 4;
    int b = self.view.frame.size.width / 8;
    int c = 30;
    
    UIButton *button1 = [[UIButton alloc] initWithFrame:CGRectMake(a - b - c, 10, 60, 60)];
//    [button setFrame:CGRectMake(x*row-60-((x-60)/2), y, 60, 70)];
    [button1 setImage:[UIImage imageNamed:buttonPhotoArray[0]] forState:UIControlStateNormal];
    [button1 addTarget:self action:@selector(luntanEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button2 = [[UIButton alloc] initWithFrame:CGRectMake(a * 2 - b - c, 10, 60, 60)];
    [button2 setImage:[UIImage imageNamed:buttonPhotoArray[1]] forState:UIControlStateNormal];
    [button2 addTarget:self action:@selector(youxueEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button3 = [[UIButton alloc] initWithFrame:CGRectMake(a * 3 - b - c, 10, 60, 60)];
    [button3 setImage:[UIImage imageNamed:buttonPhotoArray[2]] forState:UIControlStateNormal];
    [button3 addTarget:self action:@selector(zixunEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UIButton *button4 = [[UIButton alloc] initWithFrame:CGRectMake(a * 4 - b - c, 10, 60, 60)];
    [button4 setImage:[UIImage imageNamed:buttonPhotoArray[3]] forState:UIControlStateNormal];
    [button4 addTarget:self action:@selector(chuangtouEvent) forControlEvents:UIControlEventTouchUpInside];
    
    UILabel *label1 = [[UILabel alloc]initWithFrame:CGRectMake(a - b - c, 55, 60, 35)];
    label1.font =  [UIFont boldSystemFontOfSize:13.0f];
    label1.textAlignment = NSTextAlignmentCenter;
    label1.text = buttonNameArray[0];
    
    
    UILabel *label2 = [[UILabel alloc]initWithFrame:CGRectMake(a * 2 - b - c, 55, 60, 35)];
    label2.textAlignment = NSTextAlignmentCenter;
    label2.text = buttonNameArray[1];
    label2.font =  [UIFont boldSystemFontOfSize:13.0f];
    
    UILabel *label3 = [[UILabel alloc]initWithFrame:CGRectMake(a * 3 - b - c, 55, 60, 35)];
    label3.textAlignment = NSTextAlignmentCenter;
    label3.text = buttonNameArray[2];
    label3.font =  [UIFont boldSystemFontOfSize:13.0f];
    
    UILabel *label4 = [[UILabel alloc]initWithFrame:CGRectMake(a * 4 - b - c, 55, 60, 35)];
    label4.textAlignment = NSTextAlignmentCenter;
    label4.text = buttonNameArray[3];
    label4.font =  [UIFont boldSystemFontOfSize:13.0f];
    
    [ButtonView addSubview:button1];
    [ButtonView addSubview:button2];
    [ButtonView addSubview:button3];
    [ButtonView addSubview:button4];
    [ButtonView addSubview:label1];
    [ButtonView addSubview:label2];
    [ButtonView addSubview:label3];
    [ButtonView addSubview:label4];
    ButtonView.backgroundColor = [UIColor whiteColor];
    
    changeCityButton = [[UIButton alloc] initWithFrame:CGRectMake(self.view.frame.size.width - 100, 100, 90, 40)];
    [changeCityButton setImage:[UIImage imageNamed:@"changeCity"] forState:UIControlStateNormal];
//    [changeCityButton setBackgroundImage:[UIImage imageNamed:@"icon02@2x.png"] forState:UIControlStateNormal];
    [changeCityButton addTarget:self action:@selector(changeCity) forControlEvents:UIControlEventTouchUpInside];
}

- (void)changeCity
{
    //设置通知，显示城市选择的pickView
    [[NSNotificationCenter defaultCenter] postNotificationName:@"changeCity" object:self userInfo:nil ];
}

//四个点击事件,从本地到俱乐部的具体界面
- (void)luntanEvent{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setInteger:0 forKey:@"buttonTagNumber"];
    [userDefault synchronize];//存入文件
    
    [UserDefaults setObject:@"notClube" forKey:@"whereComeForm"];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *MainCell=[story instantiateViewControllerWithIdentifier:@"ClubeShowTableViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:MainCell];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)youxueEvent{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setInteger:1 forKey:@"buttonTagNumber"];
    [userDefault synchronize];//存入文件
    
    [UserDefaults setObject:@"notClube" forKey:@"whereComeForm"];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *MainCell=[story instantiateViewControllerWithIdentifier:@"ClubeShowTableViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:MainCell];
    [self presentViewController:nav animated:YES completion:nil];
}

- (void)zixunEvent{
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setInteger:2 forKey:@"buttonTagNumber"];
    [userDefault synchronize];//存入文件
    
    [UserDefaults setObject:@"notClube" forKey:@"whereComeForm"];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *MainCell=[story instantiateViewControllerWithIdentifier:@"ZhiXunViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:MainCell];
    [self presentViewController:nav animated:YES completion:nil];
 
}

- (void)chuangtouEvent{
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    [userDefault setInteger:3 forKey:@"buttonTagNumber"];
    [userDefault synchronize];//存入文件

    [UserDefaults setObject:@"notClube" forKey:@"whereComeForm"];
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    LoginViewController *MainCell=[story instantiateViewControllerWithIdentifier:@"ClubeShowTableViewController"];
    UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:MainCell];
    [self presentViewController:nav animated:YES completion:nil];

}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


-(void)setSlug:(NSString *)slug{
    
    NSLog(@"--slug--%@",slug);
    NSLog(@"--self.tableView--%@",self.tableView);
    [UserDefaults setObject:@"center" forKey:@"center"];//刷新在中间
//    self.tableView =
    if (slug!=nil) {
        [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeClear];
        [topArray removeAllObjects];
        _slug=slug;
        isLoading=NO;
        //        [SVProgressHUD show];
        
        [self doneLoadingViewData];
    }else{
        _slug=slug;
       
    }
    
    
    for (NSDictionary *abc in cityArray) {
        //                [@"catdir"]
        if ([_slug isEqualToString:abc[@"catdir"]]  ) {
            //                self.tableView = theTableView;
            
            NSLog(@"self.view.frame.size.width %f",self.view.frame.size.width);
            if (self.tableView.frame.origin.x ==  self.view.frame.size.width) {
                theTableView = self.tableView;
                NSLog(@"theTableView == %@",theTableView);
//                [self initData ];
//                self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
//                self.tableView.backgroundColor=[UIColor whiteColor];
//                self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
//                EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(self.tableView.frame.origin.x,99, self.tableView.frame.size.width, 0)];
//                view.delegate = self;
//                [self.tableView addSubview:view];
//                self.refreshHeaderView = view;
//                [self initData ];
//                NSLog(@"++self.tableView++%@",self.tableView);
//                id table = self.tableView;
//                [UserDefaults setObject:table forKey:@"theTableView"];
//                self.tableView.frame =
            }
            
        }}
}
-(void)reloadTableView{
    
    
    [self doneLoadingViewData];
}
#pragma mark - 头图初始化
-(void)initPscroll{
    NSMutableArray*array=[[NSMutableArray alloc]init];
    for (int i=0;i<5;i++) {
        PageImageView*view=[[PageImageView alloc]init];
        view.ID=@"";
        view.PCatid=@"";
        view.URL=@"11";
        view.PTitle=@"";
        
        [array addObject:view];
    }
    float h = 165;
    if (self.view.frame.size.width>320) {
        h+=45;
    }
    Pscroll = [[PageControlScrollView alloc]initWithFrame:CGRectMake(0, 99, self.view.frame.size.width, h) pictures:array whichView:@"news"];
    Pscroll.delegate = self;
    
    [self initFourButton];
}

-(void)initData{
    self.title=@"看商界";
    UITabBarItem*it= self.tabBarController.tabBar.items[0];
    it.title=@"精选";
    
    _userData=[[NSMutableArray alloc]init];
    topArray=[[NSMutableArray alloc]init];
    cityArray = [[NSArray alloc] init];
//    theTableView = [[UITableView alloc] init];
//    NSLog(@"first theTableView %@",theTableView);
    
    _page=1;
    NSLog(@"CGRectZero -- %@",CGRectZero);
    self.tableView.tableFooterView=[[UIView alloc]initWithFrame:CGRectZero];
    self.tableView.backgroundColor=[UIColor whiteColor];
    self.tableView.separatorStyle=UITableViewCellSeparatorStyleNone;
    EGORefreshTableHeaderView *view = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(self.tableView.frame.origin.x,99, self.tableView.frame.size.width, 0)];
    view.delegate = self;
    [self.tableView addSubview:view];
    self.refreshHeaderView = view;
    
    
 
}

#pragma mark - 网络数据请求方法
-(void)loadNews{
    NSLog(@"开始加载");
    
    if(isLoading){
        [SVProgressHUD dismiss];
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
        return;
    }
    
    
    //获取保存到单例的本地城市的名字
    cityArray = [NSArray arrayWithArray:[UserDefaults objectForKey:@"cityNameArray"]];
    if ([cityArray count] > 0) {
        
    }
    else{
//        cityArray = [NSArray arrayWithObjects:@"郑州",@"重庆",nil];
    }
    
    isLoading = YES;
    NSString*url;
    NSMutableDictionary*parameter;
    if (_page==1) {
        parameter=[@{@"p":[NSString stringWithFormat:@"%d",_page],@"top":@"1"} mutableCopy];
    }else{
        parameter=[@{@"p":[NSString stringWithFormat:@"%d",_page]} mutableCopy];
    }
    NSLog(@"self.slug!= %@",self.slug);
    if (self.slug!=nil) {
        [parameter setObject:self.slug forKey:@"slug"];
        if ([self.slug isEqualToString:@"quyujingji"]) {
            [parameter setObject:@"1" forKey:@"local"];
        }
        //        if ([slugKey isEqualToString:@"col"]) {
        //            [parameter removeObjectForKey:@"top"];
        //        }
        url=@"Category/News";
    }else{
        url=@"Category/Main";
    }
    
   


    NSLog(@"parameter -- %@",parameter);
    NSLog(@"");
    
//    url=@"Category/News";
//    parameter=[@{@"p":[NSString stringWithFormat:@"%d",_page],@"top":@"1"} mutableCopy];
//    NSDictionary *parDic = [[NSDictionary alloc]initWithObjectsAndKeys: @"1",@"p",@"",@"slug",@"1",@"top", nil];
//    p = 1;
//    slug = "";
//    top = 1;
    [[AppAPIClient sharedClient] GET:url parameters:parameter success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSMutableDictionary *result = responseObject[@"data"];
        
        NSLog(@"result -=-= %@",result);
        NSLog(@"parameter ==++ %@",parameter);
        NSLog(@"operation ==++ %@",operation);
        
        //        NSLog(@"result ++ %@",result);
        //        NSLog(@"responseObject ++ %@",responseObject);
        
        if([result isKindOfClass:[NSNull class]] || [result count] == 0||[result[@"content"] count]==0){
            [SVProgressHUD dismiss];
            [self.tableView reloadData];
            [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
            //            reloading = NO;
            //            isLoading=NO;
            return;
        }
        
        if(_userData.count==0){
//            _userData = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
            
            
            
            
            NSMutableArray *subArray1 = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
            NSMutableArray *subArray2 = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
            
            
            NSLog(@" self.slug -- %@",self.slug);
            
            if (self.slug.length > 0) {
//                                [_userData addObjectsFromArray:result[@"content"]];
                 _userData = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
                NSLog(@" self.slug -- %@",self.slug);
            }
            else{
                
                NSDictionary *SubtractDic = [[NSDictionary alloc]init];
                id subId;
                //删除包含重庆和郑州的新闻,在精选界面
                for (subId in subArray1) {
//                    NSLog(@"subId ----- %@",subId);
                    if (![(NSValue *)subId[@"catid"] isEqual: [NSNull null] ]) {
//                        NSLog(@"subId ---++--- %@",subId);
                        if ([[subId objectForKey:@"catid"] isEqualToString:@"3693"] || [[subId objectForKey:@"catid"] isEqualToString:@"3681"]) {
                            [subArray2 removeObject:subId];
                            
                        }
                     }
                }
                NSLog(@"subArray1.count %lu",(unsigned long)subArray1.count);
                NSLog(@"subArray2.count %lu",(unsigned long)subArray2.count);
//                NSLog(@"subArray1 -- %@",subArray1);
//                NSLog(@"subArray2 -- %@",subArray2);
                
                _userData = [NSMutableArray arrayWithArray:subArray2];
//                _userData = [[NSMutableArray alloc] init];
//                _userData = subArray2;
//                [_userData insertObject:@"" atIndex:0];
//                NSLog(@"_userData -- %@",_userData);//显示的所有的数据
            }
            
            [_userData insertObject:@"" atIndex:0];
        }
        
        else{
            
//            [_userData addObjectsFromArray:result[@"content"]];
            
            NSMutableArray *subArray1 = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
            NSMutableArray *subArray2 = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
            
            
            NSLog(@" self.slug -- %@",self.slug);
            
            if (self.slug.length > 0) {
                                [_userData addObjectsFromArray:result[@"content"]];
//                 _userData = [[NSMutableArray alloc]initWithArray:result[@"content"] copyItems:YES];
                NSLog(@" self.slug -- %@",self.slug);
            }
            else{
                
                NSDictionary *SubtractDic = [[NSDictionary alloc]init];
                id subId;
                for (subId in subArray1) {
//                    NSLog(@"subId ----- %@",subId);
                    if (![(NSValue *)subId[@"catid"] isEqual: [NSNull null] ]) {
//                        NSLog(@"subId ---++--- %@",subId);
                        if ([[subId objectForKey:@"catid"] isEqualToString:@"3693"] || [[subId objectForKey:@"catid"] isEqualToString:@"3681"]) {
                            [subArray2 removeObject:subId];
                            
                        }
                    }
                }
                NSLog(@"subArray1.count %lu",(unsigned long)subArray1.count);
                NSLog(@"subArray2.count %lu",(unsigned long)subArray2.count);
//                NSLog(@"subArray1 -- %@",subArray1);
//                NSLog(@"subArray2 -- %@",subArray2);
                
                [_userData addObjectsFromArray:subArray2];
//                _userData = [NSMutableArray arrayWithArray:subArray2];
                //                _userData = [[NSMutableArray alloc] init];
                //                _userData = subArray2;
//                [_userData insertObject:@"" atIndex:0];
//                NSLog(@"_userData -- %@",_userData);//显示的所有的数据
            }
            
        }
        _page++;
        NSLog(@"_page++ %d",_page);
        if (topArray.count==0) {
            topArray=[[NSMutableArray alloc]initWithArray:responseObject[@"data"][@"top"] copyItems:YES];
            NSMutableArray*array=[[NSMutableArray alloc]init];
           
            ///滚动头图
            for (NSDictionary*dic in topArray) {
                PageImageView*view=[[PageImageView alloc]init];
                view.All_Dic=dic;
                view.ID=dic[@"id"];
                view.PCatid=dic[@"catid"];
                view.imageUrl=dic[@"thumb"];
                view.PTitle=dic[@"title"];
                view.URL=dic[@"url"];
//                [array addObject:view];
//                [array insertObject:view atIndex:0];
                [array addObject:view];
            }
            
            ///广告
            for (NSDictionary*dic in [UserDefaults objectForKey:@"ad"][@"data"][@"alist"]) {
                if ([dic[@"type"] integerValue]==3) {
                    PageImageView*view=[[PageImageView alloc]init];
                    view.All_Dic=dic;
                    //                    view.ID=dic[@"id"];
                    view.imageUrl=dic[@"typeval"];
                    NSArray *arr = [dic[@"name"] componentsSeparatedByString:@"|"];
                    view.PTitle=arr[1];
                    //                    view.PTitle = dic[@"name"];
                    view.URL=dic[@"value"];
                    [array addObject:view];
                    //                    [array insertObject:view atIndex:3];
                }
            }
            
            [Pscroll refresh:array];
            
        }
        
        
//         [_userData insertObject:@"" atIndex:0];
        
        [SVProgressHUD dismiss];
        isLoading = NO;
        reloading = NO;
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
        
//        for (NSDictionary *abc in cityArray) {
//            //                [@"catdir"]
//            if ([_slug isEqualToString:abc[@"catdir"]]  ) {
////                self.tableView =
//                theTableView = [UserDefaults objectForKey:@"theTableView"];//从单例中取出来
//                NSLog(@"thechange theTableView %@",theTableView);
////                [theTableView reloadData];
//                [self.tableView reloadData];
//                return;
//            }
//            
//            
//        }
        
        NSLog(@"self.tableView reloadData %@",self.tableView);
        NSLog(@"_userData =-+_ %@",_userData); 
        [self.tableView reloadData];
        
        NSLog(@"加载完成");
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"ERR: %@",operation.responseString);
        isLoading = NO;
        reloading = NO;
        [SVProgressHUD showErrorWithStatus:@"网络错误"];
        [self.refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:self.tableView];
    }];
    

}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    //#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if ([_userData count]) {
        return [_userData count];
    }else{
        return 0;
    }
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row==0) {
        float h = 264;
        
        //如果这个界面请求的网络数据为本地
//         NSString *theCityName = [[UserDefaults objectForKey: @"local"] objectForKey:@"catdir"];
//        if (_slug.length > 1) {
//            if ([_slug isEqualToString:theCityName]  ) {
//                h +=90;
//            }
//        }
        
        NSLog(@"slug =-09 %@",_slug);
        if (_slug.length > 1) {
            
            for (NSDictionary *abc in cityArray) {
//                [@"catdir"]
               
                if ([_slug isEqualToString:abc[@"catdir"]] || [_slug isEqualToString:@"quyujingji"]) {
                    h = 354;
                    
                }
                
                }
        }
        
        if (self.view.frame.size.width>320) {
            h+=55;
        }
        return h;
    }
    
    
    //    NSInteger fa = indexPath.row;
    if (indexPath.row>=_userData.count) {
        return 0;
    }
    long int type =0;
    NSInteger row = indexPath.row;
    
    BOOL image = false;
    if ( ![[_userData[indexPath.row] objectForKey:@"thumb"] isKindOfClass:[NSNull class]] ) {
        image =[[_userData[indexPath.row] objectForKey:@"thumb"] length]>6;
    }
    //判断服务器的这个数据是不是为空
   
    
    if ([_userData[indexPath.row][@"type"] isEqualToString:@"news"]) {
        BOOL description;
        if (![[_userData[row] objectForKey:@"description"] isKindOfClass:[NSNull class]]) {
            description = [[_userData[row] objectForKey:@"description"] length]>3;
        
        if (description&&image) {
            type=2;
        }else if (description){
            type=5;
        }else if (image){
            type=6;
        }else{
            type=1;
        }
        }
        
    }else if([_userData[indexPath.row][@"type"] isEqualToString:@"large"]){
        
        type = 4;
    }
    
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"video"]){
        
        type = 11;//视频的标志
    }
    
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"soft"]){
        
        type = 22;//软文的标志
    }
    
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"ad1"]){
        
        type = 33;//没有简介的广告的标志,无转发
    }
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"ad2"]){
        
        type = 44;//有简介的广告的标志,无转发
    }
    else{
        type = 3;
    }
    //-----------------------------------------------------------
    if (type==1) {
        return 65;
    }else if (type==2||type==5||type==6 || type == 11 || type == 22) {
        return 95;
    }else if (type==3) {
        return 140;
    }else if (type==33||type==4) {
        
        NSString *whiceIphone = [UserDefaults objectForKey: @"iphoneTheHight"];
        
        if ([whiceIphone isEqualToString:@"iphone5"]) {
            return 163;//183
        }
        if ([whiceIphone isEqualToString:@"iphone6"]) {
            return 170;//200
        }
        if ([whiceIphone isEqualToString:@"iphone6p"]) {
            return 185;//211
        }
        return 200;
        
    }else if (type==44) {
        
        NSString *whiceIphone = [UserDefaults objectForKey: @"iphoneTheHight"];
        
        if ([whiceIphone isEqualToString:@"iphone5"]) {
            return 205;//183
        }
        if ([whiceIphone isEqualToString:@"iphone6"]) {
            return 210;//200
        }
        if ([whiceIphone isEqualToString:@"iphone6p"]) {
            return 225;//211
        }
        return 200;
        
    }else{
        return 0;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell * cell;
    if(indexPath.row == [_userData count]-2){
        [SVProgressHUD showWithStatus:@"数据加载中..." maskType:SVProgressHUDMaskTypeClear];
        [self loadNews];
    }
    
    
    
    
    //    NSLog(@"fffffffff----%@",_userData[indexPath.row][@"title"]);
    if (indexPath.row==0) {
        cell=[tableView dequeueReusableCellWithIdentifier:@"cell"];
        if(cell==nil){
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        }
 
        cell.contentView.backgroundColor= [UIColor colorWithRed:246 green:246 blue:246 alpha:1];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        [cell.contentView addSubview:Pscroll];
        
      

        //如果这个界面请求的网络数据为本地  chengdu
        NSLog(@"_slug --++ %@",_slug);
        NSString *theCityName = [[UserDefaults objectForKey: @"local"] objectForKey:@"catdir"];
        NSLog(@"theCityName == %@",theCityName);
  
        if (_slug.length > 1) {
            
            for (NSDictionary *abc in cityArray) {
                //                [@"catdir"]
                if ([_slug isEqualToString:abc[@"catdir"]] || [_slug isEqualToString:@"quyujingji"]) {
//                    NSLog(@"")
                    [cell.contentView addSubview:ButtonView];
                    [cell.contentView addSubview:changeCityButton];
                    
                }
                
            }
        }

        //当界面成为本地时
 
        
        return cell;
    }
    long int type =0;
    BOOL description ;
//    BOOL image =[[_userData[indexPath.row] objectForKey:@"thumb"] length]>6;

    BOOL image = false;
    if ( ![[_userData[indexPath.row] objectForKey:@"thumb"] isKindOfClass:[NSNull class]] ) {
        image =[[_userData[indexPath.row] objectForKey:@"thumb"] length]>6;
    }
    //判断服务器的这个数据是不是为空
    
//    NSLog(@"_userData ---===--- %@",_userData);
    
    if ([_userData[indexPath.row][@"type"] isEqualToString:@"news"]) {
        if (![[_userData[indexPath.row] objectForKey:@"description"] isKindOfClass:[NSNull class]]) {
            description = [[_userData[indexPath.row] objectForKey:@"description"] length]>3;
            
        if (description&&image) {
            type=2;
        }else if (description){
            type=5;
        }else if (image){
            type=6;
        }else{
            type=1;
        }
        }
    }else if([_userData[indexPath.row][@"type"] isEqualToString:@"large"]){
        
        type = 4;
    }
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"video"]){
        
        type = 11;//视频的标志
    }
    
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"soft"]){
        
        type = 22;//软文的标志
    }
    
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"ad1"]){
        
        type = 33;//没有简介的广告的标志,无转发
    }
    else if([_userData[indexPath.row][@"type"] isEqualToString:@"ad2"]){
        
        type = 44;//有简介的广告的标志,无转发
    }
    
    else{
        type = 3;
    }
    
    if (type==1) {
        cell= [self.tableView dequeueReusableCellWithIdentifier:@"cell1"];
        if (cell==nil) {
            cell=[self.tableView dequeueReusableCellWithIdentifier:@"cell1"  forIndexPath:indexPath];
            
        }
    }else if (type==2) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell2" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell2"];
        }
    }else if (type==3) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell3" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell3"];
        }
    }else if (type==4) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell4" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell4"];
        }
    }else if (type==5) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell5" forIndexPath:indexPath];
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell5"];
        }
    }else if (type==6) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"cell6" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"cell6"];
        }
    }
    else if (type==11) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"voide" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"voide"];
        }
    }
    else if (type==22) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"soft" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"soft"];
        }
    }
    else if (type==33) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"ad1" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"ad1"];
        }
    }
    else if (type==44) {
        cell= [tableView dequeueReusableCellWithIdentifier:@"ad2" forIndexPath:indexPath];
        NSLog(@"-- indexPath -- %@",indexPath);
        
        if (cell==nil) {
            cell=[tableView dequeueReusableCellWithIdentifier:@"ad2"];
        }
    }
//    cell.backgroundColor=UIColorFromRGB(0xf5f5f5);
    
        cell.backgroundColor = [UIColor whiteColor];
    if (type==1) {
        return [self LoadDataType1:tableView Cell:cell IndexPath:indexPath];
    }else if (type==2 || type==11 || type==22 ) {
        return [self LoadDataType2:tableView Cell:cell IndexPath:indexPath];
    }else if (type==3) {
        return [self LoadDataType3:tableView Cell:cell IndexPath:indexPath];
    }else if (type==4 || type==33) {
        return [self LoadDataType4:tableView Cell:cell IndexPath:indexPath];
    }else if (type==5) {
        return [self LoadDataType5:tableView Cell:cell IndexPath:indexPath];
    }else if (type==6) {
        return [self LoadDataType6:tableView Cell:cell IndexPath:indexPath];
    }else if (type==44) {
        return [self LoadDataTypeAd2:tableView Cell:cell IndexPath:indexPath];
    }else{
        return cell;
    }
    
}

-(UITableViewCell *)LoadDataType1:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    //    NSLog(@"row---%d",indexPath.row);
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    return cell;
}



-(UITableViewCell *)LoadDataType2:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    NSLog(@"_userData[indexPath.row] == %@",_userData[indexPath.row]);
    
    
    UILabel*description=(UILabel*)[cell.contentView viewWithTag:66];

    description.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"description"]];
 
    NSMutableAttributedString * attributedString1 = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"description"]]];
    NSMutableParagraphStyle * paragraphStyle1 = [[NSMutableParagraphStyle alloc] init];
    [paragraphStyle1 setLineSpacing:3];
    [attributedString1 addAttribute:NSParagraphStyleAttributeName value:paragraphStyle1 range:NSMakeRange(0, [[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"description"]] length])];
    [description setAttributedText:attributedString1];
//    [description sizeToFit];
    
    
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview setAlpha:1];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_userData[indexPath.row][@"thumb"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(error != nil){
            [imageview setImage:[UIImage imageNamed:@"placeholderImage"]];
        }else{
            //            [UIView animateWithDuration:0.3f animations:^{
            //                [imageview setAlpha:0];
            //            } completion:^(BOOL finished) {
            [imageview setImage:image];
            //                [UIView animateWithDuration:0.3f animations:^{
            //                    [imageview setAlpha:1.0f];
            //                }];
            //            }];
        }
    }];
    return cell;
}

-(UITableViewCell *)LoadDataType3:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    
    NSDictionary*dic=_userData[indexPath.row];
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",dic[@"title"]];
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview sd_setImageWithURL:[NSURL URLWithString:dic[@"picture"][0]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] ];
    
    UIImageView*imageview2=(UIImageView*)[cell.contentView viewWithTag:55];
    [imageview2 sd_setImageWithURL:[NSURL URLWithString:dic[@"picture"][1]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] ];
    
    UIImageView*imageview3=(UIImageView*)[cell.contentView viewWithTag:66];
    [imageview3 sd_setImageWithURL:[NSURL URLWithString:dic[@"picture"][2]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] ];
    
    return cell;
}

-(UITableViewCell *)LoadDataType4:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    
    NSString *title = [NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    if (![title isKindOfClass:[NSNull class]]) {
        label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    }
    
    
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview setAlpha:1];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_userData[indexPath.row][@"thumb"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(error != nil){
            [imageview setImage:[UIImage imageNamed:@"placeholderImage"]];
        }else{
            //            [UIView animateWithDuration:0.3f animations:^{
            //                [imageview setAlpha:0];
            //            } completion:^(BOOL finished) {
            [imageview setImage:image];
            //                [UIView animateWithDuration:0.3f animations:^{
            //                    [imageview setAlpha:1.0f];
            //                }];
            //            }];
        }
    }];
    return cell;
}
-(UITableViewCell *)LoadDataType5:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    UILabel*description=(UILabel*)[cell.contentView viewWithTag:66];
    description.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"description"]];
    return cell;
}

//这里是主页的tableCell类型，在这里请求照片和text
-(UITableViewCell *)LoadDataType6:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    UILabel *label111 = (UILabel*)[cell.contentView viewWithTag:111];
    label111.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"comment"]];
    label111.hidden = YES;
    
    
    NSLog(@"_userData[0] == 在哪里%@",_userData[indexPath.row]);// - 1
    NSLog(@"indexPath ===== 是哪个？%ld",(long)indexPath.row );// - 1
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview setAlpha:1];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_userData[indexPath.row][@"thumb"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(error != nil){
            [imageview setImage:[UIImage imageNamed:@"placeholderImage"]];
        }else{
            //            [UIView animateWithDuration:0.3f animations:^{
            //                [imageview setAlpha:0];
            //            } completion:^(BOOL finished) {
            [imageview setImage:image];
            //                [UIView animateWithDuration:0.3f animations:^{
            //                    [imageview setAlpha:1.0f];
            //                }];
            //            }];
        }
    }];
    return cell;
}

//这里是主页有简介的广告
-(UITableViewCell *)LoadDataTypeAd2:(UITableView*)tableView Cell:(UITableViewCell*)cell IndexPath:(NSIndexPath *)indexPath {
    UILabel*label1=(UILabel*)[cell.contentView viewWithTag:11];
    
    NSString *title = [NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    
    UILabel*description2=(UILabel*)[cell.contentView viewWithTag:12];
    description2.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"description"]];
    
    if (![title isKindOfClass:[NSNull class]]) {
        label1.text=[NSString stringWithFormat:@"%@",_userData[indexPath.row][@"title"]];
    }
    
    
    
    UIImageView*imageview=(UIImageView*)[cell.contentView viewWithTag:44];
    [imageview setAlpha:1];
    [imageview sd_setImageWithURL:[NSURL URLWithString:_userData[indexPath.row][@"thumb"]] placeholderImage:[UIImage imageNamed:@"placeholderImage"] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        if(error != nil){
            [imageview setImage:[UIImage imageNamed:@"placeholderImage"]];
        }else{
            //            [UIView animateWithDuration:0.3f animations:^{
            //                [imageview setAlpha:0];
            //            } completion:^(BOOL finished) {
            [imageview setImage:image];
            //                [UIView animateWithDuration:0.3f animations:^{
            //                    [imageview setAlpha:1.0f];
            //                }];
            //            }];
        }
    }];
    return cell;
}


//tableCell的点击事件
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:NO];//点击后不会有阴影
    if(_userData.count==0||indexPath.row==0){
        return;
    }
    
   
    
    if([_userData[indexPath.row][@"type"] isEqualToString:@"ad1"] || [_userData[indexPath.row][@"type"] isEqualToString:@"ad2"]){
        //有简介的广告的标志,无转发
        //没有简介的广告的标志,无转发
      
        
        [UserDefaults setValue:_userData[indexPath.row][@"url"] forKey:@"AdvertisementWebsite"];
        
        
        
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
        ADWebViewController*login=[story instantiateViewControllerWithIdentifier:@"ADWebViewController"];
        UINavigationController*nav=[[UINavigationController alloc]initWithRootViewController:login];
        [self presentViewController:nav animated:YES completion:nil];
    }
    
    

    else{
        
        [UserDefaults setValue:_userData[indexPath.row][@"description"] forKey:@"description"];
        
        UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
        ArticleViewController*art=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
        NSInteger row = indexPath.row;
        art._Dict=_userData[row];
        art.isCommentVC=NO;
        art.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
        [self presentViewController:art animated:YES completion:^{
            if (self.ScrollerBlock) {
                self.ScrollerBlock(0);
            }
        }];
        }
    
    
}

#pragma mark - PageControlScrollViewDelegate
-(void)pageScrollDelegate:(PageControlScrollView*)pageScrollView didSelectindex:(int)index{
    
    NSLog(@"index ++ %d",index);
}
-(void)pageScrollDelegate:(PageControlScrollView *)pageScrollView didScrollImageView:(PageImageView*)imageview{
    //    if (imageview.PCatid.length<2) {
    //        [self performSegueWithIdentifier:@"mPweb" sender:imageview.All_Dic];
    //    }else{
    
    NSLog(@"imageview -= %@",imageview);
    
    UIStoryboard*story=[UIStoryboard storyboardWithName:@"Main" bundle:nil];
    ArticleViewController*art=[story instantiateViewControllerWithIdentifier:@"ArticleViewController"];
    art._Dict=imageview.All_Dic;
    NSLog(@"imageview.All_Dic = %@",imageview.All_Dic);
    art.isCommentVC=NO;
    art.modalTransitionStyle = UIModalTransitionStyleCrossDissolve;
    [self presentViewController:art animated:YES completion:^{
        if (self.ScrollerBlock) {
            self.ScrollerBlock(0);
        }
    }];
    //    }
}
#pragma mark -

#pragma mark - UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    
    [self.refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    NSInteger index=scrollView.contentOffset.y;
    //    NSLog(@"- %ld- -%ld",index,self.offsety);
    if (self.ScrollerBlock) {
        if (self.offsety - index>=45||index<45) {
            self.ScrollerBlock(0);
        }else if(self.offsety - index<=-65){
            self.ScrollerBlock(1);
        }
        
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    
    
    [self.refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    NSInteger index=scrollView.contentOffset.y;
    self.offsety=index ;
    
}
#pragma mark RefreshHeaderViewDelegate Methods

-(void)egoRefreshTableHeaderDidTriggerRefresh:(EGORefreshTableHeaderView *)view{
    
    
    if(reloading){
        return;
    }
    reloading=YES;
    NSLog(@"重新加载");
    [self performSelector:@selector(doneLoadingViewData) withObject:nil afterDelay:0];
    
}
- (void)doneLoadingViewData{
    
    //  model should call this when its done loading
    
    _page=1;
    reloading = NO;
    isLoading=NO;
    [topArray removeAllObjects];
    
    _userData = nil;
    
    [self loadNews];
     
    
}
-(BOOL)egoRefreshTableHeaderDataSourceIsLoading:(EGORefreshTableHeaderView *)view{
    return reloading;
}
-(NSDate *)egoRefreshTableHeaderDataSourceLastUpdated:(EGORefreshTableHeaderView *)view{
    return [NSDate date];
}



@end
